/*
 * Created on Mar 22, 2010
 */
package ro.letsdoitromania;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Display;
import ro.letsdoitromania.forms.LoginForm;
import com.mgmaps.app.PendingForm;
import com.mgmaps.app.SerialCall;
import com.mgmaps.net.HTTPForm;
import com.mgmaps.tools.StringTools;
import com.mgmaps.utils.ExtLogger;
import com.mgmaps.utils.LS;
import com.twmacinta.util.MD5;

public class TrashPointRequest extends HTTPForm {
  
  public TrashPointRequest() {
    super(LDIRSettings.UPLOAD_URL, HttpConnection.POST, "text/xml");
  }
  
  public Hashtable getAdditionalHeaders() {
    Hashtable h = super.getAdditionalHeaders();
    h.put("Authorization", "Basic " + StringTools.encodeBase64(LDIRSettings.username + ":" + 
        MD5.hashString(LDIRSettings.password + LDIRSettings.usersalt)));
    return h;
  }
  
  /**
   * Build the request content for this form.
   * 
   * @return the content as a byte array
   */
  public byte[] getRequest() throws IOException {
    StringBuffer req = new StringBuffer();
    req.append("<pilelist>");
    for (int i=0; i<LDIRSettings.points.size(); i++)
      req.append(((TrashPointData) LDIRSettings.points.elementAt(i)).buildXML());
    req.append("</pilelist>");
    
    ExtLogger.debug("WASTESERVICE REQUEST: " + req.toString());
    
    return req.toString().getBytes();
  }

  /**
   * Called when the download is complete.
   * 
   * @param data submission complete data
   * @see com.mgmaps.net.Downloadable#notifyDownloaded(byte[][])
   */
  public void notifyDownloaded(byte[][] data) {
    try {
      if (PendingForm.getInstance().isCancelled())
        ExtLogger.error("Upload cancelled");
      else {
        final String response = StringTools.byteArrayToString(data[0]);
        
        ExtLogger.debug("WASTESERVICE RESPONSE: " + response);
        
        final String[] s = StringTools.extractAllXMLChildren(StringTools.extractXMLContent(
            response, "responsewastes"), "responsewaste");
        
        // check response
        int num = LDIRSettings.points.size();
        final int initialNum = num; 
        final Vector validated = new Vector();
        for (int i=0; i<s.length; i++) {
          int id = Integer.parseInt(StringTools.extractXMLContent(s[i], "LocalID"));
          if (id <= 0 || id > num) {
            ExtLogger.error("Invalid id for point -- " + id);
            continue;
          }
          final TrashPointData tpd = ((TrashPointData) LDIRSettings.points.elementAt(id-1));
          if (tpd.getID() != id) {
            ExtLogger.error("Invalid local id for point -- " + tpd.getID() + " for point at " + (id-1));
            continue;
          }
          final String status = StringTools.extractXMLContent(s[i], "Succes");
          if (status.equals("true"))
            validated.addElement(new Integer(id));
          else
            ExtLogger.error("Failure for point -- " + id);
        }
        final int count = validated.size();
        
        // remove validated points
        for (int i=0; i<count; i++) {
          int id = ((Integer) validated.elementAt(i)).intValue();
          for (int j=0; j<num; j++)
            if (((TrashPointData) LDIRSettings.points.elementAt(j)).getID() == id) {
              LDIRSettings.points.removeElementAt(j);
              num--;
              break;
            }
        }
        LDIRSettings.updatePointIDs();
        validated.removeAllElements();
        
        Display.getDisplay(LDIRMidlet.instance).setCurrent(LDIRCanvas.instance);
        
        if (count == initialNum)
          SerialCall.instance.show(SerialCall.SC_ALERT, LS.get("ldir.upload.title"), LS.get("ldir.upload.success",
              new String[] { Integer.toString(count) }));
        else if (count > 0)
          SerialCall.instance.show(SerialCall.SC_ALERT, LS.get("ldir.upload.title"), LS.get("ldir.upload.partial",
              new String[] { Integer.toString(count), Integer.toString(initialNum) }));
        else
          SerialCall.instance.show(SerialCall.SC_ALERT, LS.get("ldir.upload.title"), LS.get("ldir.upload.failure"));
      }
    }
    catch (Exception ex) {
      notifyError("EXCEPTION: " + ex.getMessage());
    }
  }

  /**
   * Called when the download returns an error.
   * 
   * @see com.mgmaps.net.Downloadable#notifyError()
   */
  public void notifyError(String message) {
    ExtLogger.error("ERROR: " + message);

    // 401?
    if (message.equals("ERR Unauthorized")) {
      LDIRSettings.usersalt = "";
      LoginForm.getInstance().show(LS.get("ldir.login.error"));
    }
    
    else {
      Display.getDisplay(LDIRMidlet.instance).setCurrent(LDIRCanvas.instance);
      SerialCall.instance.show(SerialCall.SC_ALERT, LS.get("ldir.upload.title"), LS.get("ldir.upload.error",
          new String[] { message }));
    }
  }

}
